/**
 * Message2DbHandlerImpl.java<br>
 *
 *
 * @version 下午11:10:22
 */
package com.iwechat.service.impl;

import java.text.ParseException;
import java.util.concurrent.atomic.AtomicInteger;

import javax.annotation.PostConstruct;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iwechat.mybatis.generator.dao.TemplateMessageMapper;
import com.iwechat.mybatis.generator.model.TemplateMessage;
import com.iwechat.service.MessageHandler;

/**
 * 消息存储到数据库的handler
 *
 *
 */
@Service("message2DbHandler")
public class Message2DbHandlerImpl implements MessageHandler {
    private static final Logger logger   = LogManager.getLogger();

    @Autowired
    TemplateMessageMapper       mapper;

    private AtomicInteger       subIdAto = new AtomicInteger(0);

    @PostConstruct
    public void init() {
        logger.info("### " + this + " init succeed!");
    }

    @Override
    public int handle(TemplateMessage message) throws ParseException {
        int retcd = -1;
        // 设置消息的服务类型
        message.genServiceType();

        // 1. 实时消息直接存库并发送
        if (message.getPriority() == TemplateMessage.HIGH_PROP
                && (TemplateMessage.NO_FB_TIME.equals(message.getServiceType()) || message.canSend())) {

            message.setStatus(TemplateMessage.Status.STATUS_1_PROCESS);
            try {
                long sqlNb = mapper.getSeqNb();
                message.setSeqnb(sqlNb);
                mapper.insertAndSend(message);
            } catch (Exception e) {
                logger.error("数据库操作异常，消息将继续正常处理：" + e.getMessage());
                // 数据库操作异常，后续消息正常处理，序号程序生成
                int sub = subIdAto.getAndIncrement();
                if (sub > Integer.MAX_VALUE - 10000) {
                    subIdAto.set(0);
                    sub = 0;
                }
                long sqlNb = System.currentTimeMillis() + sub;
                message.setSeqnb(sqlNb);
            }
            // 实时消息入库成功，可以直接进行发送
            retcd = 100;
        }
        // 2. 非实时消息只存库
        else {
            mapper.insert4Scan(message);
            // 非实时消息，后续不需做处理，等待扫描发送
            retcd = 200;
        }

        return retcd;
    }

}
